package com.scalar.chiptrack.sales.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.sales.forms.AddNewContactPersonForm;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.EndUserDAO;
import com.scalar.chiptrack.sales.ContactPerson;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.User;
import com.scalar.ScalarException;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.commons.beanutils.PropertyUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Author: Prabhanjan
 * Date: Mar 18, 2004
 * Time: 6:18:57 PM
 */


public class AddNewEndUserContactPersonAction extends ChipTrackAction {

	private static final String ACTION_NAME = "/addNewEndUserContactPerson.do" ;
	private ArrayList allcontactpersons = new ArrayList();
	private String contactperson = null;

		public ActionForward execute (ActionMapping mapping,
										  ActionForm form,
										  HttpServletRequest request,
										  HttpServletResponse response)
										 throws Exception {

		HttpSession session = request.getSession();
   	  	User user = (User)session.getAttribute (SessionKeys.USER_KEY);

		 if (user == null)
		 {
			session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
			return (mapping.findForward ("login"));
		 }

		HashMap errors = new HashMap();
		request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

		HashMap info = new HashMap();
		request.setAttribute (SessionKeys.INFO_MESSAGES, info);

		AddNewContactPersonForm contactpersonform = (AddNewContactPersonForm) form;
        String action = request.getParameter("action");
		String contactPersonValue = request.getParameter("value");
		int endUserId = Integer.parseInt(request.getParameter("endUserId"));
		//System.out.println("contactPersonValue   "+contactPersonValue+"endUserId  "+endUserId);


		request.setAttribute("contactPersons",EndUserDAO.getAllEndUserContactPersonsWithActions ( endUserId , contactPersonValue) );

		if( "disable".equalsIgnoreCase( request.getParameter( "contactPersonstatus" ) ) == true )
		{
			String contactPersonToDelete = request.getParameter("contactPerson");
			if ( (contactPersonToDelete != null) && (contactPersonToDelete.trim().length() != 0 ) )
			{
				try
				{
					EndUserDAO.deleteEndUserContactPerson( contactPersonToDelete , endUserId , contactPersonValue);
					info.put (contactPersonToDelete + " has been disabled", null);
				}
				catch (ScalarException se)
				{
					se.printStackTrace ();
					errors.put ("Internal Server Error", "Could not delete \"" + contactPersonToDelete + "\"");
				}
			}
		}
		else if ("activate".equalsIgnoreCase(request.getParameter("contactPersonstatus")) == true )
		{
			String contactPersonToActivate = request.getParameter("contactPerson");
			if ((contactPersonToActivate != null) && (contactPersonToActivate.trim().length() != 0))
			{
				try
				{
				  EndUserDAO.activateEndUserContactPerson ( contactPersonToActivate , endUserId ,contactPersonValue);
				  info.put (contactPersonToActivate + " has been activated", null);
				}
				catch (ScalarException se)
				{
				  se.printStackTrace ();
				  errors.put ("Internal Server Error", "Could not activate \"" + contactPersonToActivate + "\"");
				}
  			}
		}
		if("insertContactPerson".equalsIgnoreCase(action))
		{
			contactperson = request.getParameter("newContactPerson");
            boolean success = false;
			boolean temp = false;

			if((contactperson == null) || (contactperson.trim().length() == 0)) {
				errors.put ( ERROR_CUSTOMER_INVALID_CONTACT_PERSON, null );
				return (mapping.findForward ("success"));
			}
			allcontactpersons = EndUserDAO.getAllEndUserContactPersonsWithActions( endUserId , contactPersonValue );
			int allcontactpersonsSize = allcontactpersons.size();
			ContactPerson  contactPerson = new  ContactPerson();

			for (int j=0; j<allcontactpersonsSize; j++)
			{
				contactPerson =(ContactPerson)allcontactpersons.get(j);
				String contactpersonname = contactPerson.getContactPerson();
				if( (contactperson != null) && (contactpersonname != null) )
				{
					if (contactperson.trim().equalsIgnoreCase(contactpersonname))
					{
						temp= true;
						break;
					}
				}
			}//for end

			if (temp == true) {
				errors.put ( contactperson +" " + ERROR_CUSTOMER_REP_ALREADY_EXISTS, null );
				return (mapping.findForward ("success"));
			}

			try {
                //Modified by varma(25jun2004)
				//EndUserDAO.insertEndUserContactPerson (null, endUserId ,contactpersonform.getNewContactPerson(),contactpersonform.getPhoneNumber(),contactpersonform.getCellNumber(),contactpersonform.getFaxNumber(),contactpersonform.getEmail(),contactpersonform.getAddress(),contactPersonValue);
                EndUserDAO.insertEndUserContactPerson (null, endUserId ,
													    contactperson,
													    contactpersonform.getPhoneNumber(),
													    contactpersonform.getCellNumber(),
													    contactpersonform.getFaxNumber(),
													    contactpersonform.getEmail(),
                                                        contactpersonform.getSalesAckMail(),
                                                        contactpersonform.getShipAlerts() ,
                                                        contactpersonform.getProformaInvoice() ,
                                                        contactpersonform.getPackingSlip() ,
                                                        contactpersonform.getCommerInvoice() ,
													    contactpersonform.getAddress(),
													    contactPersonValue);
				info.put ( INFO_CONTACT_PERSON_SUCCESSFULLY_STORED, null );
                success = true;
			}
			catch (ScalarException se) {
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				se.printStackTrace();
			}
			contactpersonform.setNewContactPerson("");
			contactpersonform.setPhoneNumber("");
			contactpersonform.setCellNumber("");
			contactpersonform.setFaxNumber("");
			contactpersonform.setEmail("");
            contactpersonform.setAddress( "" );
            contactpersonform.setSalesAckMail( false );
            contactpersonform.setShipAlerts( false );
            contactpersonform.setProformaInvoice( false );
            contactpersonform.setPackingSlip( false );
            contactpersonform.setCommerInvoice( false );

		}
        //added by varma 22 jul 2004 to save changes to End user Contact Person Details
        if("saveEditContactPerson".equalsIgnoreCase(action))
		{
            contactperson = request.getParameter("newContactPerson");
			boolean success = false;
			boolean temp = false;
            String oldContactPerson = (String)session.getAttribute("oldContactPerson");
			if((contactperson == null) || (contactperson.trim().length() == 0)) {
				errors.put ( ERROR_CUSTOMER_INVALID_CONTACT_PERSON, null );
				return (mapping.findForward ("success"));
			}
            if(CustomerDAO.isContactPersonExists( contactperson, contactPersonValue, endUserId, oldContactPerson ) )
            {
                errors.put ( "ContactPerson","Contact Person Already Exists with Name "+contactperson ) ;
                contactpersonform.setNewContactPerson( oldContactPerson );
                contactpersonform.setAction("editContactPerson");
				return (mapping.findForward ("success"));
            }
		    try
            {

				CustomerDAO.changeContactPersonDetails (null, endUserId ,
													    contactpersonform.getNewContactPerson(),
													    contactpersonform.getPhoneNumber(),
													    contactpersonform.getCellNumber(),
													    contactpersonform.getFaxNumber(),
													    contactpersonform.getEmail(),
                                                        contactpersonform.getSalesAckMail(),
                                                        contactpersonform.getShipAlerts() ,
                                                        contactpersonform.getProformaInvoice() ,
                                                        contactpersonform.getPackingSlip() ,
                                                        contactpersonform.getCommerInvoice() ,
													    contactpersonform.getAddress(),
													    contactPersonValue,
                                                        oldContactPerson, false,false);
				info.put ( INFO_CONTACT_PERSON_SUCCESSFULLY_STORED, null );
				success = true;
			}
			catch (ScalarException se) {
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				se.printStackTrace();
			}
			contactpersonform.setNewContactPerson("");
			contactpersonform.setPhoneNumber("");
			contactpersonform.setCellNumber("");
			contactpersonform.setFaxNumber("");
			contactpersonform.setEmail("");
            contactpersonform.setAddress( "" );
            contactpersonform.setSalesAckMail( false );
            contactpersonform.setShipAlerts( false );
            contactpersonform.setProformaInvoice( false );
            contactpersonform.setPackingSlip( false );
            contactpersonform.setCommerInvoice( false );


		}
        //added by varma on 22 jul 2004 to Edit End User Contact person Details
        if("editContactPerson".equalsIgnoreCase(action) )
        {
            String contactPersontoEdit = request.getParameter("contactPerson");
            session.setAttribute("oldContactPerson",contactPersontoEdit);
            if ( (contactPersontoEdit != null) && (contactPersontoEdit.trim().length() != 0 ) )
			{
				try
				{
                    ContactPerson contactPerson = CustomerDAO.editContactPerson( contactPersontoEdit , endUserId ,contactPersonValue );
                    PropertyUtils.copyProperties ( contactpersonform, contactPerson );
                    contactpersonform.setNewContactPerson( contactPerson.getContactPerson() );

				}
				catch (ScalarException se)
				{
					se.printStackTrace ();
					errors.put ("Internal Server Error", "Could not get Data to Edit \"" + contactPersontoEdit + "\"");
				}
			}

        }
		request.setAttribute("contactPersons",EndUserDAO.getAllEndUserContactPersonsWithActions( endUserId, contactPersonValue ));
		request.setAttribute("addNewContactPersonForm",contactpersonform);
        return (mapping.findForward ("success"));
	}



}
